package com.hifar.test.equituit.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hifar.fw.utils.id.IdUtils;
import com.hifar.fw.utils.lang.StringUtils;
import com.hifar.plat.baseModal.service.IBaseOssFilesService;
import com.hifar.plat.officUtil.ExcelTemplateUtil;
import com.hifar.test.equituit.pojo.EquipUnitSearchVo;
import com.hifar.test.equituit.pojo.HfResEquipUnit;
import com.hifar.test.equituit.pojo.HfResEquipUnitVo;
import com.hifar.test.equituit.service.IHfResEquipUnitService;
import com.hifar.sys.*;
import com.hifar.test.unit.pojo.HfPrjUnitBase;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 设备-项目-关闭表 前端控制器 default
 * </p>
 *
 * @author wangkepeng
 * @since 2024-12-18 14:14:04
 */
@RestController
@RequestMapping("/api/busi/test/hfResEquipUnitController")
@Api(tags = "设备-项目-关闭表功能")
public class HfResEquipUnitController {

    @Autowired
    private IHfResEquipUnitService hfResEquipUnitService;

    @Autowired
    private IBaseOssFilesService baseOssFilesService;

    @PostMapping(value = "/list")
    @ApiOperation(value = "设备-项目-关闭表功能:分页查询列表")
    public BusiResponse list(HttpServletRequest request) {
        Map<String, Object> pageInfo = RequestConver.getPageInfo(request);

        String equipId = StringUtils.trimNull(pageInfo.get("equipId"));
        QueryWrapper<EquipUnitSearchVo> queryWrapper = RequestConver.getPostParam(pageInfo);
        queryWrapper.ne("del_flag", "1");
        if (!"".equals(equipId)) {
            queryWrapper.eq("equip_id", equipId);
        }
        queryWrapper.orderByDesc("create_time");
        queryWrapper.in("secret_level", SystemLoginUser.dataSecretSet);
        if (queryWrapper != null && pageInfo.size() > 0) {
            Page<EquipUnitSearchVo> page = new Page<>((Integer) pageInfo.get("pageNo"),
                    (Integer) pageInfo.get("pageSize"));
            Page<EquipUnitSearchVo> page1 = hfResEquipUnitService.selectEntityVoPage(page, queryWrapper);
            /* 计算分页信息返回给前端 */
            PageResult pageResult = SystemUtil.parsePage(page, page1);
            return BusiResponse.OK(pageResult);
        } else {
            return BusiResponse.error("参数不正确！");
        }
    }

    @PostMapping(value = "/listAll")
    @ApiOperation(value = "设备-项目-关闭表功能:查询列表(不带分页)")
    public BusiResponse listAll(HttpServletRequest request) {

        Map<String, Object> pageInfo = RequestConver.getPageInfo(request);

        String equipId = StringUtils.trimNull(pageInfo.get("equipId"));

        QueryWrapper<EquipUnitSearchVo> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        queryWrapper.ne("del_flag", "1");
        queryWrapper.in("secret_level", SystemLoginUser.dataSecretSet);
        if (!"".equals(equipId)) {
            queryWrapper.eq("equip_id", equipId);
        }
        List<EquipUnitSearchVo> list = hfResEquipUnitService.listEntityVo(queryWrapper);

        if (list != null && list.size() > 0) {
            return BusiResponse.OK(list);
        } else {
            return BusiResponse.ok("没有查询到数据！");
        }
    }

    @PostMapping(value = "/listData")
    @ApiOperation(value = "设备-项目-关闭表功能:分页查询列表")
    public BusiResponse listData(HttpServletRequest request) {
        Map<String, Object> pageInfo = RequestConver.getPageInfo(request);

        String equipId = StringUtils.trimNull(pageInfo.get("equipId"));
        QueryWrapper<HfResEquipUnit> queryWrapper = RequestConver.getPostParam(pageInfo);
        queryWrapper.ne("del_flag", "1");
        if (!"".equals(equipId)) {
            queryWrapper.eq("equip_id", equipId);
        }
        queryWrapper.orderByDesc("create_time");
        queryWrapper.in("secret_level", SystemLoginUser.dataSecretSet);
        if (queryWrapper != null && pageInfo.size() > 0) {
            Page<HfResEquipUnit> page = new Page<>((Integer) pageInfo.get("pageNo"),
                    (Integer) pageInfo.get("pageSize"));
            Page<HfResEquipUnit> page1 = hfResEquipUnitService.page(page, queryWrapper);
            page1.getRecords().forEach(item -> {
            });
            /* 计算分页信息返回给前端 */
            PageResult pageResult = SystemUtil.parsePage(page, page1);
            return BusiResponse.OK(pageResult);
        } else {
            return BusiResponse.error("参数不正确！");
        }
    }

    @PostMapping(value = "/listAllData")
    @ApiOperation(value = "设备-项目-关闭表功能:查询列表(不带分页)")
    public BusiResponse listAllData(HttpServletRequest request) {

        Map<String, Object> pageInfo = RequestConver.getPageInfo(request);

        String equipId = StringUtils.trimNull(pageInfo.get("equipId"));

        QueryWrapper<HfResEquipUnit> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        queryWrapper.ne("del_flag", "1");
        queryWrapper.in("secret_level", SystemLoginUser.dataSecretSet);
        if (!"".equals(equipId)) {
            queryWrapper.eq("equip_id", equipId);
        }
        List<HfResEquipUnit> list = hfResEquipUnitService.list(queryWrapper);

        list.forEach(item -> {
        });
        if (list != null && list.size() > 0) {
            return BusiResponse.OK(list);
        } else {
            return BusiResponse.ok("没有查询到数据！");
        }
    }

    @PostMapping(value = "/add")
    @ApiOperation(value = "设备-项目-关闭表功能:新增")
    public BusiResponse add(@RequestBody HfResEquipUnit hfResEquipUnit) {
        hfResEquipUnitService.save(hfResEquipUnit);
        return BusiResponse.ok("添加成功");
    }

    @PostMapping(value = "/addVo")
    @ApiOperation(value = "设备-项目-关闭表功能:新增")
    public BusiResponse addVo(@RequestBody HfResEquipUnitVo hfResEquipUnitVo) {

        HfResEquipUnit hfResEquipUnit = null;

        // 查询历史数据
        QueryWrapper<HfResEquipUnit> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("del_flag", 0);
        queryWrapper.eq("equip_id", hfResEquipUnitVo.getEquipId());
        List<HfResEquipUnit> dataList = hfResEquipUnitService.list(queryWrapper);
        Set<String> unitIdExistSet = dataList.stream().map(item -> item.getUnitId()).collect(Collectors.toSet());

        List<HfResEquipUnit> equipUnitList = new ArrayList<HfResEquipUnit>();
        List<HfPrjUnitBase> unitList = hfResEquipUnitVo.getUnitList();
        if (unitList != null) {
            for (HfPrjUnitBase unit : unitList) {
                if (!unitIdExistSet.contains(unit.getId())) {
                    hfResEquipUnit = new HfResEquipUnit();
                    hfResEquipUnit.setId(IdUtils.uuid32());
                    hfResEquipUnit.setUnitId(unit.getId());
                    hfResEquipUnit.setEquipId(hfResEquipUnitVo.getEquipId());
                    hfResEquipUnit.setCreateUserId(SystemLoginUser.userId);
                    hfResEquipUnit.setCreateUserName(SystemLoginUser.idName);
                    hfResEquipUnit.setCreateTime(new Date());
                    hfResEquipUnit.setUpdateUserId(SystemLoginUser.userId);
                    hfResEquipUnit.setUpdateUserName(SystemLoginUser.idName);
                    hfResEquipUnit.setUpdateTime(new Date());
                    equipUnitList.add(hfResEquipUnit);
                }
            }
        }
        hfResEquipUnitService.saveBatch(equipUnitList);
        return BusiResponse.ok("添加成功");
    }

    @PostMapping(value = "/edit")
    @ApiOperation(value = "设备-项目-关闭表功能:编辑")
    public BusiResponse edit(@RequestBody HfResEquipUnit hfResEquipUnit) {
        hfResEquipUnitService.updateById(hfResEquipUnit);
        return BusiResponse.ok("编辑成功！");
    }

    @GetMapping("/queryById")
    @ApiOperation(value = "设备-项目-关闭表功能:根据id查询数据")
    public BusiResponse queryById(@RequestParam(name = "id") String id) {
        // HfResEquipUnit byId = hfResEquipUnitService.getById(id);

        QueryWrapper<EquipUnitSearchVo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        List<EquipUnitSearchVo> list = hfResEquipUnitService.listEntityVo(queryWrapper);

        EquipUnitSearchVo byId = null;
        if (list != null && list.size() > 0) {
            byId = list.get(0);
        }
        // 查询转换附件
        return BusiResponse.OK(byId);
    }

    @PostMapping("/delete")
    @ApiOperation(value = "设备-项目-关闭表功能:逻辑删除")
    public BusiResponse delete(@RequestBody List<String> idList) {
        QueryWrapper<HfResEquipUnit> delete = new QueryWrapper<>();
        delete.in("id", idList);
        hfResEquipUnitService.remove(delete);
        return BusiResponse.ok("删除成功！");
    }

    @PostMapping("/exportExcel")
    @ApiOperation(value = "设备-项目-关闭表功能:导出数据")
    public Object exportExcel(HttpServletRequest request) {
        Map<String, Object> pageInfo = RequestConver.getPageInfo(request);
        if (pageInfo == null) {
            return BusiResponse.error("参数有误！");
        }
        BusiResponse export = hfResEquipUnitService.exportExcel(pageInfo);
        if (export.getCode() == com.hifar.fw.utils.bean.BusiConst.CODE_SUCCESS) {
            String encode = null;
            try {
                encode = URLEncoder.encode("设备-项目-关闭表.xlsx", "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type", "application/vnd.ms-excel");
            headers.add("Access-Control-Expose-Headers", "Content-Disposition");
            headers.add("Content-Disposition", "filename=" + encode);
            return ResponseEntity.status(HttpStatus.OK).headers(headers).body((byte[]) export.getData());
        }
        return export;
    }

    @PostMapping("/importExcel")
    @ApiOperation(value = "设备-项目-关闭表功能:导入excel数据")
    public BusiResponse importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return BusiResponse.error("文件为空！");
        } else {
            if (ExcelTemplateUtil.isExcelFile(file)) {
                return hfResEquipUnitService.importExcel(file);
            } else {
                return BusiResponse.error("请上传excel文件！");
            }
        }
    }

}